package com.mud.dnd.frontend.web.mbeans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.primefaces.model.UploadedFile;

import com.mud.dnd.domain.common.DAOException;
import com.mud.dnd.domain.common.QueryParameter;
import com.mud.dnd.domain.common.QueryParameter.QueryParamOperator;
import com.mud.dnd.domain.model.Action;
import com.mud.dnd.domain.model.Card;
import com.mud.dnd.domain.model.CardAction;
import com.mud.dnd.domain.model.Deck;
import com.mud.dnd.ejb.CardManager;
import com.mud.dnd.ejb.CommentManager;
import com.mud.dnd.ejb.PictureManager;
import com.mud.dnd.ejb.UserManager;
import com.mud.dnd.ejb.common.AuthenticationException;



@ManagedBean( name = "myCardsBean")
@SessionScoped
public class MyCardsBean extends AbstractCardsBean {

	@EJB
	private UserManager userManager;
	
	@EJB 
	private CommentManager commentManager;
	
	@EJB 
	private CardManager cardManager;
	
	@EJB
	private PictureManager pictureManager;
	
	
	private String userName;
	private String password;
	
	private long selectedPage = 0;
	
	
	private String output;
	
	private boolean loggedIn = false;
	private boolean userIsAdmin = false;
	private String sessionID;
	
	private String commentMessage;
	
	private String adminUserName;
	private String adminPassword;
	
	private UploadedFile uploadedFile;
	

	public MyCardsBean() {
		clearSelectedCard();
		clearSelectedDeck();
		clearSelectedAction();
	}
	
	public String selectPage(long index) {
		selectedPage = index;
		switch ((int)index) {
		case 1:
			return "/web/game";
		case 2:
			return "/web/cards";
		case 3:
			return "/web/admindecks";
		case 4:
			return "/web/admincards";
		case 5:
			return "/web/adminactions";
		case 6:
			return "/web/adminpage";

		default:
			return "/index";
		}

	}
	
	
	public void loginUser()
	{
		try {
			sessionID = userManager.loginUser(userName, password);
			output = "OK";
			loggedIn = true;
			userIsAdmin= userManager.checkIfUserAdmin(userName);
			
		} catch (DAOException e) {
			output = "Error during login!: "+e.getMessage();
		} catch (AuthenticationException e) {
			output = "Wrong user name or password!";
		}catch(Exception e)
		{
			output = "Error during login!";
		}
	}
	
	public String loginForward()
	{
		loginUser();
		if(loggedIn)
		{
			return "/index";
		}else
		{
			return null;
		}
		
	}
	
	public void registerUser()
	{
		
		try {
			userManager.createUser(userName, password);
			output = "New user registered!: "+userName;
		} catch (DAOException e) {
			output = "Error during registration!: "+e.getMessage();
		} catch (AuthenticationException e) {
			output = e.getMessage();
		}catch(Exception e)
		{
			output = "Error during resgistration!";
		}
	}
	
	public String logoutUser()
	{
		
		try {
			userManager.logoutUser(userName, sessionID);
			output = "";
			userName = "";
			password = "";
			loggedIn = false;
			userIsAdmin = false;
		} catch (DAOException e) {
			output = "Error during registration!: "+e.getMessage();
		} catch (AuthenticationException e) {
			output = e.getMessage();
		}
		
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		
		return "/index";
		
	}
	
	public void createAdminUser()
	{
		 try {
			userManager.createAdminUser(adminUserName, adminPassword, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
	}
	
	public void deleteUser()
	{
		try {
			userManager.deleteUser(userName, adminUserName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		
	}
	
	public void addComment(int gameItemID  )
	{
		try {
			commentManager.addComment(commentMessage, userName, gameItemID, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		
		commentMessage = "";
	}
	
	
	
	 public void addRating(int rating, int cardID) {  
	       
		 try {
			cardManager.updateCard(cardID, null, null, null, null,((int) rating), 0, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		 
	  } 
	 

	@Override
	public void searchDeck() {
		List<QueryParameter> params = new ArrayList<QueryParameter>();
		try {
			if(searchDeckName!=null && (!searchDeckName.equals("")) )
			{
				params.add(new QueryParameter("name",QueryParamOperator.LIKE,searchDeckName));
			}
			if(searchDeckDesc!=null && (!searchDeckDesc.equals("")))
			{
				params.add(new QueryParameter("description",QueryParamOperator.LIKE,searchDeckDesc));
			}
			params.add(new QueryParameter("author",QueryParamOperator.LIKE,userName));
		} catch (DAOException e) {
			deckOutput = e.getMessage();
		}
		
		decks = deckManager.getDecks(params);
	}
	
	public void deleteDeck()
	{
		try {
			deckManager.deleteDeck(selectedDeck.getId(), userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		
		clearSelectedDeck();
		searchDeck();
	}
	
	public void createDeck()
	{
		try {
			deckManager.createDeck(selectedDeck.getName(), selectedDeck.getDescription(), selectedDeck.getPictureURL(), userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		searchDeck();
	}
	
	public void updateDeck()
	{
		try {
			deckManager.updateDeck(selectedDeck.getId(), selectedDeck.getName(), selectedDeck.getDescription(), selectedDeck.getPictureURL(),0,userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		searchDeck();
	}
	
	
	public void deleteCard()
	{
		try {
			
			cardManager.deleteCard(selectedCard.getId(), userName, sessionID);
			
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		
		clearSelectedCard();
		//searchCard();
	}
	
	public void removeCardfromDeck()
	{
		try {
			if(selectedCard.getDeckIDs()==null)
			{
				return;
			}
			else
			{
				cardManager.removeCardfromDeck(selectedCard.getId(),selectedDeck.getId(), userName, sessionID);
			}
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		clearSelectedCard();
		searchCardInDeck(cards);
	}
	
	public void addCardtoDeck()
	{
		try {
			if(selectedDeck==null)
			{
				return;
			}
			else
			{
				cardManager.addCardtoDeck(selectedCard.getId(),selectedDeck.getId(), userName, sessionID);
			}
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		clearSelectedCard();
		searchCardInDeck(cards);
	}
	
	public void createCard()
	{
		try {
			cardManager.createCard(selectedCard.getName(), selectedCard.getDescription(), selectedCard.getPictureURL(),"action",0, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		//searchCard();
	}
	
	public void updateCard()
	{
		try {
			cardManager.updateCard(selectedCard.getId(),selectedCard.getName(), selectedCard.getDescription(), selectedCard.getPictureURL(),"action",0,0, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		//searchCard();
	}
	
	public void deleteAction()
	{
		try {
			
			actionManager.deleteAction(selectedAction.getId(), userName, sessionID);
			
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		
		clearSelectedAction();
		searchActionInCard(actions,cardActions);
	}
	
	public void removeActionfromCard()
	{
		try {
			
			actionManager.removeActionfromCard(selectedAction.getId(),selectedCard.getId(), userName, sessionID);
			
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		clearSelectedAction();
		searchActionInCard(actions,cardActions);
	}
	
	public void addActiontoCard()
	{
		try {
			if(selectedCard==null)
			{
				return;
			}
			else
			{
				actionManager.addActiontoCard(selectedAction.getId(),selectedCard.getId(),selectedActionAmount, userName, sessionID);
			}
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		clearSelectedAction();
		searchActionInCard(actions,cardActions);
	}
	
	public void createAction()
	{
		try {
			actionManager.createAction(selectedAction.getName(), selectedAction.getDescription(), selectedAction.getPictureURL(), userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		searchAction(actions,cardActions);
	}
	
	public void updateAction()
	{
		try {
			actionManager.updateAction(selectedAction.getId(),selectedAction.getName(), selectedAction.getDescription(), selectedAction.getPictureURL(),0, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		searchAction(actions,cardActions);
	}
	
	
	public void updateActionInCard()
	{
		updateActionInCard(selectedAction.getId(),selectedCard.getId(),0,0);

	}
	
	
	public void updateActionInCard(int actionId, int cardId, int amount ,long order)
	{
		try {
			actionManager.updateActionInCard(actionId,cardId,amount,(int)order, userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		}
		searchActionInCard(actions,cardActions);
	}
	
	
	
	
	public void uploadCard(int id)
	{
		String fileName = FilenameUtils.getName(uploadedFile.getFileName());
        String contentType = uploadedFile.getContentType();
        byte[] bytes = uploadedFile.getContents();
        
        try {
			pictureManager.addPicture(fileName, bytes,  id,userName, sessionID);
		} catch (DAOException e) {
			 showErrorMessage(e.getMessage());
		} catch (AuthenticationException e) {
			 showErrorMessage(e.getMessage());
		} catch (IOException e) {
			 showErrorMessage(e.getMessage());
		}
		
	}
	
	
	private void clearSelectedDeck()
	{
		
		selectedDeck = new Deck("DeckName", "DeckDesc", "http://th00.deviantart.net/fs33/200H/f/2008/240/b/5/Dragon_of_spirits_by_Ruth_Tay.jpg", null);
	}
	
	private void clearSelectedCard()
	{
		
		selectedCard = new Card("CardName", "CardDesc", "http://th00.deviantart.net/fs33/200H/f/2008/240/b/5/Dragon_of_spirits_by_Ruth_Tay.jpg", "CardType", 0, null);
	}
	
	private void clearSelectedAction()
	{
		
		selectedAction = new Action("CardName", "CardDesc","http://th00.deviantart.net/fs33/200H/f/2008/240/b/5/Dragon_of_spirits_by_Ruth_Tay.jpg", null);
	}
	
	


	public String getSessionID() {
		return sessionID;
	}

	public void setSessionID(String sessionID) {
		this.sessionID = sessionID;
	}

	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isLoggedIn() {
		return loggedIn;
	}
	public void setLoggedIn(boolean loggedIn) {
		this.loggedIn = loggedIn;
	}


	public String getOutput() {
		return output;
	}


	public void setOutput(String output) {
		this.output = output;
	}

	public String getCommentMessage() {
		return commentMessage;
	}

	public void setCommentMessage(String commentMessage) {
		this.commentMessage = commentMessage;
	}


	public boolean isUserIsAdmin() {
		return userIsAdmin;
	}


	public void setUserIsAdmin(boolean userIsAdmin) {
		this.userIsAdmin = userIsAdmin;
	}


	public String getAdminUserName() {
		return adminUserName;
	}


	public void setAdminUserName(String adminUserName) {
		this.adminUserName = adminUserName;
	}


	public String getAdminPassword() {
		return adminPassword;
	}


	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}


	public long getSelectedPage() {
		return selectedPage;
	}


	public void setSelectedPage(int selectedPage) {
		this.selectedPage = selectedPage;
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}
	
	
	
	
}
